package com.kch.web.controller.system;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.kch.system.req.SysUserAddReq;
import com.kch.system.req.SystemUserReq;
import com.kch.system.vo.SysUserRestPwd;
import com.kch.system.vo.SysUserVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.kch.common.annotation.Log;
import com.kch.common.constant.UserConstants;
import com.kch.common.core.controller.BaseController;
import com.kch.common.core.domain.AjaxResult;
import com.kch.common.core.page.TableDataInfo;
import com.kch.common.enums.BusinessType;
import com.kch.common.utils.poi.ExcelUtil;
import com.kch.framework.shiro.service.SysPasswordService;
import com.kch.framework.util.ShiroUtils;
import com.kch.system.domain.SysUser;
import com.kch.system.service.ISysRoleService;
import com.kch.system.service.ISysUserService;

/**
 * 用户信息
 *
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    private String prefix = "system/user";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;


    @Autowired
    private SysPasswordService passwordService;

    private final static String lowReg = "[a-z]+";
    private final static String upReg = "[A-Z]+";
    private final static String digReg = "[0-9]+";
    private final static String spe = "[!@#$%^&*_~]+";

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUser user) {
        user.setUserType("00");
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysUserAddReq req) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(req.getLoginName()))) {
            return error("新增用户'" + req.getLoginName() + "'失败，登录账号已存在");
        }else if(!req.getPassword().equals(req.getReppassword())){
            return error("新增用户'" + req.getLoginName() + "'失败，密码和重复密码不一致");
        }
        checkPasswd(req.getReppassword());
        SysUser user = new SysUser();
        user.setLoginName(req.getLoginName());
        user.setUserName(req.getUserName());
        user.setPassword(req.getPassword());
        user.setSalt(ShiroUtils.randomSalt());
        user.setUserType("00");
        user.setStatus("0");
        user.setDelFlag("0");
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysUserAddReq req) {
        if(ObjectUtils.isEmpty(req.getUserId())){
            return error("修改用户id不能为空");
        }
        SysUser user = new SysUser();
        user.setUserId(Long.valueOf(req.getUserId()));
        userService.checkUserAllowed(user);
        if(!userService.checkLoginName(req.getUserId(), req.getLoginName())){
            return error("修改用户'" + req.getLoginName() + "'失败，登录名已经存在");
        }else if(!req.getPassword().equals(req.getReppassword())){
            return error("修改用户'" + req.getLoginName() + "'失败，密码和重复密码不一致");
        }
        checkPasswd(req.getReppassword());
        user.setLoginName(req.getLoginName());
        user.setUserName(req.getUserName());
        user.setPassword(req.getPassword());
        user.setSalt(ShiroUtils.randomSalt());
        user.setUserType("00");
        user.setStatus("0");
        user.setDelFlag("0");
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(userService.updateUser(user));
    }


    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @GetMapping("/resetPwd")
    public String resetPwd(ModelMap mmap) {
        mmap.put("user", userService.selectUserById(ShiroUtils.getUserId()));
        return prefix + "/resetPwd";
    }

    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUserRestPwd req) {
        SysUser user = userService.selectUserById(Long.valueOf(req.getUserId()));
        userService.checkUserAllowed(user);
        if(!req.getNewPassword().equals(req.getRepPassword())){
            return error("修改密码'" + req.getLoginName() + "'失败，密码和重复密码不一致");
        }
        checkPasswd(req.getNewPassword());
        String oldPwd = passwordService.encryptPassword(user.getLoginName(), req.getOldPassword(), user.getSalt());
        if(!oldPwd.equals(user.getPassword())){
            return error("旧密码有误，请重新输入");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), req.getNewPassword(), user.getSalt()));
        if (userService.resetUserPwd(user) > 0) {
            if (ShiroUtils.getUserId() == user.getUserId()) {
                ShiroUtils.setSysUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(userService.deleteUserByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user) {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user) {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysUser user) {
        userService.checkUserAllowed(user);
        return toAjax(userService.changeStatus(user));
    }

    @GetMapping("/outer")
    public String outer() {
        return prefix + "/outerUser";
    }

    @PostMapping("/outerList")
    @ResponseBody
    public TableDataInfo outerList(SystemUserReq user) {
        user.setUserType("11");
        startPage();
        List<SysUserVO> list = userService.selectOuterUserList(user);
        return getDataTable(list);
    }

    @GetMapping("/status")
    @ResponseBody
    public AjaxResult status(Integer id) {
        userService.updateStatus(id);
        return AjaxResult.success();
    }


    public static void checkPasswd(String passwd){
        if(passwd.length() < 8 || passwd.length() > 30){
            throw new RuntimeException("长度在8-30位");
        }
        Matcher matcher;
        Pattern lowPattern = Pattern.compile(lowReg);
        matcher = lowPattern.matcher(passwd);
        if(!matcher.find()){
            throw new RuntimeException("必须包含小写字母");
        }

        Pattern upPattern = Pattern.compile(upReg);
        matcher = upPattern.matcher(passwd);
        if(!matcher.find()){
            throw new RuntimeException("必须包含大写字母");
        }

        Pattern digPattern = Pattern.compile(digReg);
        matcher = digPattern.matcher(passwd);
        if(!matcher.find()){
            throw new RuntimeException("必须包含数字");
        }

        Pattern spePatter = Pattern.compile(spe);
        matcher = spePatter.matcher(passwd);
        if(!matcher.find()){
            throw new RuntimeException("必须包含特殊字符");
        }
    }

    public static void main(String[] args) {



    }
}